package FillMythMetadataNfoFileReader;
use strict;

sub locate_thetvdb_data_in_file
{
	my $possible_nfo = $_[0];
	open NFO_FILE, "<", $possible_nfo;
	my @file_lines = <NFO_FILE>;
	close NFO_FILE;
	foreach(@file_lines)
	{
		my $a_line = $_;
		if ($a_line =~ m/<thetvdb seriesid="(\d+)"\/>/i)
		{
			#print "Found seriesid = $1\n";
			return ($1, "", "", "");
		}
		elsif ($a_line =~ m/<thetvdb seriesid="(\d+)" season="(\d+)" episode="(\d+)"\/>/i)
		{
			#print "Found seriesid=$1, season=$2, episode=$3\n";
			return ($1, $2, $3, "");
		}
		elsif ($a_line =~ m/<thetvdb episodeid="(\d+)"\/>/i)
		{
			#print "Found episodeid=$1\n";
			return ("", "", "", $1);
		}
	}
	#no data in file in file
	return ("", "", "", "");
}

my $cached_nfo_folder = "";
my $cached_nfo_folder_series_id = "";
sub locate_thetvdb_series_id_in_any_nfo_file
{
	my $folder = $_[0];
	if ($cached_nfo_folder eq $folder)
	{
	        print "Returning cached series ID '$cached_nfo_folder_series_id' for folder '$folder'\n";
	        return $cached_nfo_folder_series_id;
	}
	#my $search_path = $folder."*.nfo";
	print "Will look at '$folder'\n";
	opendir(DIR, $folder);
	my @all_nfo_files = grep { /\.nfo$/ } readdir(DIR);
	closedir(DIR);
	#globbing does not work when files/folders contain spaces.
	#my @all_nfo_files = glob($search_path);
	foreach(@all_nfo_files)
	{
		my $possible_nfo = $folder.$_;
		print "nfo: '$possible_nfo'\n";
		#looking for series id inside the file (open for read)
		my ($seriesid, $season, $episode, $episode_id) = locate_thetvdb_data_in_file($possible_nfo);
		if (length $seriesid > 0)
		{
			print "Found id=$seriesid in file $possible_nfo, will not search for the searies in THETVDB.\n";
			#saving for future calls
			$cached_nfo_folder = $folder;
			$cached_nfo_folder_series_id = $seriesid;
			return $seriesid;
		}
	}
	#did not find - caching this too..
	$cached_nfo_folder = $folder;
	$cached_nfo_folder_series_id = "";
	return "";
}

sub is_simple_meta_data
{
	my $possible_nfo = $_[0];
	if (-e $possible_nfo)
	{
		open NFO_FILE, "<", $possible_nfo;
		my @file_lines = <NFO_FILE>;
		close NFO_FILE;
		foreach(@file_lines)
		{
			my $a_line = $_;
			if ($a_line =~ m/<simple_update\/>/i)
			{
				return 1;
			}
		}
	}
	return 0;
}

sub is_skip_file
{
	my $possible_nfo = $_[0];
	if (-e $possible_nfo)
	{
		open NFO_FILE, "<", $possible_nfo;
		my @file_lines = <NFO_FILE>;
		close NFO_FILE;
		foreach(@file_lines)
		{
			my $a_line = $_;
			if ($a_line =~ m/<no_update\/>/i)
			{
				return 1;
			}
		}
	}
	return 0;
}

sub locate_imdb_data_in_file
{
	my $possible_nfo = $_[0];
	open NFO_FILE, "<", $possible_nfo;
	my @file_lines = <NFO_FILE>;
	close NFO_FILE;
	foreach(@file_lines)
	{
		my $a_line = $_;
		#I just need the digit code.
		if ($a_line =~ m/<imdb id="\D*(\d+)\D*"\/>/i)
		{
			#print "Found imdb id = $1\n";
			return $1;
		}
	}
	return "";
}

1;